import mysql.connector
from mysql.connector import Error

from LogConfig import logger

DB_CONFIG = {
	"host": "rm-9yx364w4ey002550o.mysql.rds.ops.lysjfw.chnenergy.com.cn",
	"port": 3306,
	"user": "admin01",  # 修正了键名
	"password": "Clypglj!#%246",  # 修正了键名
	"database": "OCR_CER",  # 使用database替代db
	"charset": "utf8"
}


class SQLManager:
	def __init__(self):
		self.conn = None
		self.cursor = None
		self.connect()

	def connect(self):
		try:
			self.conn = mysql.connector.connect(**DB_CONFIG)
			self.cursor = self.conn.cursor(dictionary=True)  # 使用dictionary=True替代DictCursor
		except Error as e:
			logger.error(f"数据库连接错误: {e}")
			raise

	def get_list(self, sql, args=None):
		try:
			self.cursor.execute(sql, args)
			result = self.cursor.fetchall()
			return result
		except Error as e:
			logger.error(f"查询错误: {e}")
			self.conn.rollback()
			raise

	def get_one(self, sql, args=None):
		try:
			self.cursor.execute(sql, args)
			result = self.cursor.fetchone()
			return result
		except Error as e:
			logger.error(f"查询错误: {e}")
			self.conn.rollback()
			raise

	def modify(self, sql, args=None):  # 修正了方法名拼写
		try:
			self.cursor.execute(sql, args)
			self.conn.commit()
		except Error as e:
			logger.error(f"执行错误: {e}")
			self.conn.rollback()
			raise

	def multi_modify(self, sql, args=None):
		try:
			self.cursor.executemany(sql, args)
			self.conn.commit()
		except Error as e:
			logger.error(f"批量执行错误: {e}")
			self.conn.rollback()
			raise

	def create(self, sql, args=None):
		try:
			self.cursor.execute(sql, args)
			self.conn.commit()
			last_id = self.cursor.lastrowid
			return last_id
		except Error as e:
			logger.error(f"创建错误: {e}")
			self.conn.rollback()
			raise

	def close(self):
		if self.cursor:
			self.cursor.close()
		if self.conn:
			self.conn.close()

	def __enter__(self):
		return self

	def __exit__(self, exc_type, exc_val, exc_tb):
		self.close()


if __name__ == '__main__':
	# 查询示例
	with SQLManager() as db:
		results = db.get_list("SELECT * FROM test")
		logger.info(results)
